package cn.tedu.ivos.web.controller;
import cn.tedu.ivos.base.constant.CacheConstants;
import cn.tedu.ivos.base.constant.Constants;
import cn.tedu.ivos.base.constant.HttpStatus;
import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.security.context.AuthenticationContextHolder;
import cn.tedu.ivos.base.utils.StringUtils;
import cn.tedu.ivos.pojo.dto.LoginParam;
import cn.tedu.ivos.pojo.vo.LoginUser;
import cn.tedu.ivos.service.template.CacheTemplate;
import cn.tedu.ivos.service.template.TokenTemplate;
import cn.tedu.ivos.web.model.RestResult;
import cn.tedu.ivos.web.model.RestResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class LoginController {
    @Resource
    private AuthenticationManager authenticationManager;
    @Autowired
    private TokenTemplate tokenTemplate;

    @Autowired
    private CacheTemplate cacheTemplate;
    /**
     * 登录方法
     */
    @PostMapping("/login")
    public RestResult login(@RequestBody LoginParam loginParam)
    {
        System.out.println("loginParam:"+loginParam);
        validateCaptcha(loginParam.getUsername(), loginParam.getCode(), loginParam.getUuid());
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(loginParam.getUsername(), loginParam.getPassword());
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }  finally {
            AuthenticationContextHolder.clearContext();
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return RestResultUtils.success(tokenTemplate.createToken(loginUser));
    }

    public void validateCaptcha(String username, String code, String uuid)
    {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = cacheTemplate.getCacheObject(verifyKey);
            if (captcha == null) {
               //记录登录日志
                throw new ServiceException("验证码失效", HttpStatus.CAPTCHA_EXPIRED);
            }
            cacheTemplate.deleteObject(verifyKey);
            if (!code.equalsIgnoreCase(captcha)) {
                //记录登录日志
                throw new ServiceException("验证码不正确",HttpStatus.CAPTCHA_ERR);
            }
    }

}
